import type { Translate } from '@renderer/service'
import { post } from '@renderer/utils';

enum Locale {
    'auto' = 'auto',
    'zh-CN' = 'zh-CN',
    'en-US' = 'en-US',
    'zh-TW' = 'zh-TW'
}

export default class GoogleTranslate implements Translate {
    public readonly name = "谷歌翻译"
	public readonly id = crypto.randomUUID()
    public readonly delay = 0;
    translate(keywords: string, to: string, from: string='auto'){
        const params = this.createParams(keywords, to, from)
        return new Promise<TranslateResponse>((resolve,reject) => {
            post<string>('https://google-translate.zhongjiannan.workers.dev/_/TranslateWebserverUi/data/batchexecute', params, {
                responseType: 'text',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(res => {
                res = res.replace(")]}'", '')
                const parsed = JSON.parse(JSON.parse(res)[0][2]);
                const data = parsed[1][0][0][5][0][0]
                resolve({ status: 'success', from, to, keywords, data })
            }).catch(e => {
                if(e instanceof PromiseRejectionEvent) reject(new Error(e.reason))
				if(e instanceof Error) reject(new Error(e.message))
            })
        })
    };

    createParams(keywords: string, to: string, from: string){
        const value = '[[["MkEWBc","[[\\"' + keywords + '\\",\\"' + Locale[from] + '\\",\\"' + Locale[to] + '\\",1],[]]",null,"generic"]]]'
        return { 'f.req': value}
    }
} 